package com.zgj.netty_udp.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Log4j2
@Component
public class UdpServer implements ApplicationRunner {
    private Integer udpPort = 8086;

    //server线程组
    private final Bootstrap bootstrap;
    //client线程组
    private final NioEventLoopGroup group;

    private Channel channel;

    private void Start() throws InterruptedException {
        try {
            channel = bootstrap.bind("0.0.0.0", udpPort).sync().channel();
            System.out.println("UdpServer:"+ udpPort+" start success");
            channel.closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static final class NettyUdpServerHolder {
        static final UdpServer INSTANCE = new UdpServer();
    }

    public static UdpServer getInstance() {
        return NettyUdpServerHolder.INSTANCE;
    }

    private UdpServer() {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 100)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new NettyUdpServerHandler());
                    }
                });
    }
    @Override
    public void run(ApplicationArguments args) throws Exception {
        UdpServer.getInstance().Start();
    }
}
